﻿using System.Collections.Generic;
using System.Linq;
using System.Windows;
using HappyBa.Core;
using HappyBa.Core.Data;
using HappyBa.Core.Interfaces;
using LightInject;
using Mnk.Library.Common.UI.Model;
using Mnk.Library.Common.UI.ModelsContainers;

namespace HappyBa.Pages
{
    /// <summary>
    /// Interaction logic for SearchOptionsPage.xaml
    /// </summary>
    public partial class SearchOptionsPage 
    {
        private IDataCache dataCache;
        private Search config;
        private readonly IServiceContainer container;

        public SearchOptionsPage()
        {
            InitializeComponent();
            container = ((MainWindow)Application.Current.MainWindow).Container;
            container.GetInstance<IDataCollector>().OnDataChanged += (o, e) => OnDataContextChanged(o, new DependencyPropertyChangedEventArgs());
            DataContextChanged += OnDataContextChanged;
        }

        private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            dataCache = container.GetInstance<IDataCache>();
            var cfg = container.GetInstance<Config>().Current;
            if (cfg == null) return;
            config = cfg.Search;
            Roles.ItemsSource = config.Roles;
            RolesPanel.View = Roles;
            States.ItemsSource = config.States;
            StatesPanel.View = States;
            Users.ItemsSource = config.Users;
            UsersPanel.View = Users;

            RefreshItems(config.Roles, dataCache.Metrics.Roles);
            RefreshItems(config.States, dataCache.Metrics.States);
            RefreshItems(config.Releases, dataCache.Metrics.Projects);
            RefreshItems(config.Users, dataCache.Metrics.Users);
        }

        private void RefreshItems(CheckableDataCollection<CheckableData> exists, IEnumerable<string> source)
        {
            var notChecked = exists.Where(x=>!x.IsChecked).Select(x=>x.Key).ToArray();
            exists.Clear();
            foreach (var item in source)
            {
                exists.Add(new CheckableData { Key = item, IsChecked = !notChecked.Contains(item) });
            }
        }

        private void RefreshItems<T>(CheckableDataCollection<CheckableData<int>> exists, IEnumerable<T> source)
            where T : Base
        {
            var notChecked = exists.Where(x => !x.IsChecked).Select(x => x.Value).ToArray();
            exists.Clear();
            foreach (var item in source)
            {
                exists.Add(new CheckableData<int> { Key = item.ToString(), Value = item.Id, IsChecked = !notChecked.Contains(item.Id) });
            }
        }

    }
}
